import 'package:customer/db/entity/CustomerBill.dart';
import 'package:customer/extension/extension_widget.dart';
import 'package:customer/theme.dart';
import 'package:customer/utils/snackbar.dart';
import 'package:fluent_ui/fluent_ui.dart';
import 'package:flutter_gen/gen_l10n/gyy_local.dart';

import '../../constant/edit_constant.dart';
import '../../db/entity/AttributeBean.dart';
import '../../db/entity/CustomerBillAttr.dart';
import '../../db/entity/ProductBean.dart';
import '../../main.dart';
import '../../widgets/gyy_dialog.dart';
import '../../widgets/gyy_theme.dart';
import '../../widgets/page.dart';
import 'bill_list_product.dart';
import 'drop_product_list.dart';

/// 客户改单

class EditBillPage extends StatefulWidget {
  final int id;
  final String name;
  final String phone;

  const EditBillPage(this.id, this.name, this.phone, {Key? key}) : super(key: key);

  @override
  State<EditBillPage> createState() => _EditBillPageState();
}

class _EditBillPageState extends State<EditBillPage> with PageMixin {
  TextEditingController customerController = TextEditingController(); //客户名称
  TextEditingController phoneController = TextEditingController(); //客户电话
  var customerBillDao = database.customerBillDao;
  var customerBillAttrDao = database.customerBillAttrDao;
   List<CustomerBillAttr> customerAttrList = [];

  //产品code -> 产品属性map
  Map<ProductBean, Map<String, AttributeBean>> productAttrMap = {};
  bool isOpen = false;

  //加载订单的扩展属性
  Future<List<CustomerBillAttr>> loadChildren(int billId) async {
    customerAttrList = await customerBillAttrDao.findByBillId(billId);
     return customerAttrList;
  }

  //保存客户订单
  saveCustomerBill(BuildContext context) async {
    // debugPrint('keys = ' + productAttrMap.keys.toString());
    // debugPrint('values = ' + productAttrMap.values.toString());
    var customerName = customerController.text;
    var customerPhone = phoneController.text;
    if (customerName.isEmpty || customerPhone.isEmpty) {
      showMessage(context, StringConstant.inputCustomer);
      return;
    }

    // 产品扩展属性
    // if (productAttrMap.isEmpty) {
    //   showMessage(context, StringConstant.inputProductAttr);
    //   return;
    // }
    //保存运单
    var customerBill = CustomerBill(
      customerName: customerName,
      customerPhone: customerPhone,
      price: 200,
      billDeposit: 50,
      billBalance: 150,
      billDesc: '广告3件，大幅画1件',
      createTime: DateTime.now(),
      updateTime: DateTime.now(),
    );
    int billId = await customerBillDao.insertOne(customerBill);

    //保存运单属性
    List<CustomerBillAttr> attrList = [];
    //循环每一个产品对应的扩展属性
    productAttrMap.forEach((product, attrMap){
      //循环产品的属性
      attrMap.forEach((_, attribute){
        var billAttr = CustomerBillAttr(
          billId: billId,
          productId: product.id!,
          productName: product.productName,
          productCode: product.productCode,
          attributeId: 0,
          attributeValue: attribute.attributeValue,
          attributeName: attribute.attributeName,
          attributeCode: attribute.attributeCode,
          createTime: DateTime.now(),
          updateTime: DateTime.now(),
        );
        attrList.add(billAttr);
      });

    });
    await customerBillAttrDao.insertList(attrList);

    showMessage(context, StringConstant.saveSuccess);
  }

  @override
  void initState() {
    super.initState();
    loadChildren(widget.id); //加载所有产品
    customerController.text = widget.name;
    phoneController.text = widget.phone;
  }

  @override
  Widget build(BuildContext context) {
    final theme = FluentTheme.of(context);
    return ScaffoldPage.scrollable(
      header: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          sizeBoxV10,
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              spacer,
              Text(StringConstant.edit, style: theme.typography.title, ),
              spacer,
              IconButton(icon: const Icon(FluentIcons.chrome_close), onPressed: (){
                Navigator.pop(context, DialogConstant.cancel);
              })
            ],
          ),

        ],
      ).padding(paddingH20),
      children: [
        sizeBoxV10,
        Row(
          children: [
            Expanded(
                flex: 5, child: GyyTextInput(StringConstant.customerName, customerController)),
            sizeBoxH5,
            Expanded(
                flex: 5, child: GyyTextInput(StringConstant.customerPhone, phoneController)),
            sizeBoxH5,
            FilledButton(
                child: const Text(StringConstant.saveSuccess),
                onPressed: () async {
                  saveCustomerBill(context);
                })
          ],
        ),
        sizeBoxV10,
        Row(children: [
          spacer,
          subtitle0(
              content: Text(
                '合计：200￥',
                style: TextStyle(color: AppTheme.accentColor),
              )),
        ],),

        FutureBuilder<List<CustomerBillAttr>>(
          future: loadChildren(2),
          builder: (context, snapshot) {
            if (snapshot.data == null || snapshot.data!.isEmpty) {
              return sizeBox;
            } else {
              return Column(
                children: [
                  ...buildSelectedProducts(snapshot.data!)
                ],
              );
            }
          },
        )
      ],
    );
  }

  //构建订单的产品
  List<Widget> buildSelectedProducts(List<CustomerBillAttr> customerBillAttrs) {

    List<Widget> widgets = [];
    //产品code -> 产品属性map
    Map<String, List<CustomerBillAttr>> productAttrMap = {};
    for (var element in customerBillAttrs) {
      if (!productAttrMap.containsKey(element.productCode)) {
        //productAttrMap 添加productCode
        productAttrMap[element.productCode] = [element];
      } else {
        //productAttrMap 取出productCode对应的map，添加数据
        productAttrMap[element.productCode]?.add(element);
      }
    }
    //循环每一个 产品-属性map
    productAttrMap.forEach((element, list) {
      debugPrint(element);
      debugPrint(list.toString());

      var billProductPage = BillProductDropPage(list, readOnly: false,);
      widgets.add(billProductPage);
    });

    return widgets;
  }

}
